﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NapCardOnline.Models;

namespace NapCardOnline.Controllers
{
    public class ContactController : Controller
    {
        private NapCardOnlineEntities db = new NapCardOnlineEntities();

        //
        // GET: /Contact/

        public ActionResult Index()
        {
            var objUser = Session["User"] as User;
            var userList = db.Contacts.Where(c => c.FK_UserID == objUser.UserID).ToList();
            return PartialView(userList);
        }
        [HttpPost]
        public JsonResult Create(string phoneNumber, string contactName)
        {
            var objUser = Session["User"] as User;
            //Check phone number exist
            var contact = Contact.GetContactByPhoneNumber(phoneNumber);
            if (contact == null)
            {
                var objContact = new Contact();
                objContact.ContactName = contactName;
                objContact.ContactNumber = phoneNumber;
                objContact.ContactDate = DateTime.Now;
                objContact.IsActive = true;
                if (objUser != null)
                    objContact.FK_UserID = objUser.UserID;
                Contact.Save(objContact);
                return Json(new { phone = objContact.ContactNumber, name = objContact.ContactName,contactId=objContact.ContactID }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { phone = string.Empty, name = string.Empty ,contactId=string.Empty}, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult Edit(string phone, string contactName,int id)
        {
            var objContact = Contact.GetContactById(id);
            if(objContact!=null)
            {
                objContact.ContactUpdateDate = DateTime.Now;
                objContact.ContactName = contactName;
                objContact.ContactNumber = phone;
                Contact.Save(objContact);
                return Json(new { phone = objContact.ContactNumber, contactName = objContact.ContactName, id=objContact.ContactID}, JsonRequestBehavior.AllowGet);
            }

            return null;
        }
        [HttpPost, ActionName("Delete")]
        public JsonResult Delete(int id)
        {
            var objContact = Contact.GetContactById(id);
            Contact.Delete(objContact);
            return Json("success", JsonRequestBehavior.AllowGet);
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}